package com.android.demo.widget;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.util.Log;


public final class HttpToolkit {
		private static final String TAG = "HttpToolkit";

		private static final int TIMEOUT_MILLISEC= 30000;
		
		// server return code
		public static int SERVER_SUCCESS = 200;
		public static int SERVER_SID_OUT_OF_DATE = 401;
		
		// URL to POST or Get from server
		private String m_strURL;
		private String m_Enc = HTTP.UTF_8;
		// response string from server
		private String m_strResponse;
		
		public HttpToolkit(String strUrl){
			m_strURL = strUrl;
		}
		public String getUrl(){
			return m_strURL;
		}
		
		public String GetResponse(){
			return m_strResponse;
		}
		public void setEnc(String enc){
			m_Enc = enc;
		}
		private int getResponseResult(HttpClient client, HttpUriRequest request) {
    		int ret = 0;
    		BufferedReader in = null;
    		try {
    			// get response code
    			HttpResponse response = client.execute(request);
    			ret = response.getStatusLine().getStatusCode();

    			// get response string
    			in = new BufferedReader(new InputStreamReader(response.getEntity()
    					.getContent(), m_Enc));
    			StringBuffer sb = new StringBuffer("");
    			String line = "";
    			String NL = System.getProperty("line.separator");
    			while ((line = in.readLine()) != null) {
    				sb.append(line + NL);
    			}
    			in.close();
    			m_strResponse = sb.toString();
    		} catch (Exception e) {
    			Log.e(TAG, e.toString());
    		} finally {
    			if (in != null) {
    				try {
    					in.close();
    				} catch (IOException ioe) {
    					Log.e(TAG, ioe.toString());
    				}
    			}
    		}

    		return ret;
    	}
		
		
        /** 
         * Do Get method, after this function end, call GetResponse to get returned string
         * 
         * @return http code from server after calling Get method
         */
        public int DoGet() { 
        	BufferedReader in = null;
        	int nRet = 0;
        	
            try{  
            	// make a client
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();  
                request.setURI(new URI(m_strURL));

                nRet = getResponseResult(client, request);
            }catch(Exception e){  
                Log.e(TAG,e.toString());
            }finally{  
                if(in != null){  
                    try{  
                        in.close();  
                    }catch(IOException ioe){  
                        Log.e(TAG, ioe.toString());  
                    }  
                }  
            }
            
            return nRet;
        } 

        
        /**
         * 	Do POST method to server, after this function end, call GetResponse to get returned string
         * 
         * @param c JSON pair to POST to server
         * 
         * @return  http code from server after calling POST method
         */
        public int DoPost(JSONObject jsonObject) {
            return DoPost(null, jsonObject, false);
        } 
        
        public int DoPost (ByteArrayEntity bytearray){
        	return DoPost(bytearray, null, false);
        }
        
        public int DoPost (){
            return DoPost(null, null, false);
        }
        
        public int DoPut(JSONObject jsonObject) {
            return DoPost(null, jsonObject, true);
        } 
        
        public int DoPut (ByteArrayEntity bytearray){
        	return DoPost(bytearray, null, true);
        }
        
        public int DoPut (){
            return DoPost(null, null, true);
        }
        
        public int DoPost (ByteArrayEntity bytearray , JSONObject jsonObject , boolean isPut){
        	int nRet = 0;
        	
            try{  
            	// make a POST client
                HttpClient client = new DefaultHttpClient();  
                HttpEntityEnclosingRequestBase request;
                request = isPut?new HttpPut(m_strURL):new HttpPost(m_strURL);  
                
                if (bytearray != null) {
                	request.setEntity(bytearray);
                }
                
                if (jsonObject != null) {
                	// get json string and pass to entigy
                    HttpEntity entity;
                    StringEntity s = new StringEntity(jsonObject.toString(), m_Enc);
                    s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    s.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, HTTP.UTF_8));
                    entity = s;
                    request.setEntity(entity);
                }
                
                nRet = getResponseResult(client, request);
      
            }catch(Exception e){  
                Log.e(TAG,e.toString());
            }finally{
            }
            
            return nRet;
        }
        
        public int DoDelete (){
        	BufferedReader in = null;  
        	int nRet = 0;
        	
            try{  
            	// make a delete client
                HttpClient client = new DefaultHttpClient();  
                HttpDelete request = new HttpDelete(m_strURL);  
                    
                // POST and get response code
                nRet = getResponseResult(client, request);
                
            }catch(Exception e){  
                Log.e(TAG,e.toString());
            }finally{
                if(in != null){  
                    try{  
                        in.close();  
                    }catch(IOException ioe){  
                        Log.e(TAG, ioe.toString());  
                    }  
                }  
            }
            
            return nRet;
        }
		public Bitmap DownLoadBitmap(){
			Bitmap mBmp = null;
			
			URL aryURI = null;
			URLConnection conn = null;
			InputStream is = null;
			
			try{
				aryURI = new URL(m_strURL);
				conn = aryURI.openConnection();
				conn.setReadTimeout(TIMEOUT_MILLISEC);
				conn.connect(); 
				is = conn.getInputStream();

				// get bitmap from input stream
				mBmp = BitmapFactory.decodeStream(is);
				is.close();
				
			}catch(Exception ex){
				Log.e(TAG, ex.toString());
			}

			return mBmp;
		}
		
		public byte[] DownLoadBytes(){
			URL aryURI = null;
			URLConnection conn = null;
			InputStream is = null;
			byte[] byteResult = null;
			try{
				aryURI = new URL(m_strURL);
				conn = aryURI.openConnection();
				conn.setReadTimeout(TIMEOUT_MILLISEC);
				conn.connect(); 
				is = conn.getInputStream();
				
				// get bitmap from input stream
				byteResult = getBytes(is);
				
			}catch(Exception ex){
				Log.e(TAG, ex.toString());
			}

			return byteResult;
		}
		public static byte[] getBytes(InputStream is)
	    throws Exception
	    {
	        byte[] data = null;
	        
	        Collection chunks = new ArrayList();
	        byte[] buffer = new byte[1024*1000];
	        int read = -1;
	        int size = 0;
	        
	        while((read=is.read(buffer))!=-1)
	        {
	            if(read>0)
	            {
	                byte[] chunk = new byte[read];
	                System.arraycopy(buffer,0,chunk,0,read);
	                chunks.add(chunk);
	                size += chunk.length;
	            }
	        }       
	        
	        if(size>0)
	        {
	            ByteArrayOutputStream bos = null;
	            try
	            {
	                bos = new ByteArrayOutputStream(size);
	                for(Iterator itr=chunks.iterator();itr.hasNext();)
	                {
	                    byte[] chunk = (byte[])itr.next();
	                    bos.write(chunk);
	                }
	                data = bos.toByteArray();
	            }
	            finally
	            {
	                if(bos!=null)
	                {
	                    bos.close();
	                }
	            }
	        }
	        return data;
	    }
		
		/**
		 * network tools
		 * */
		public static boolean isWifiEnable( Context context ) {
			WifiManager wifiManager = (WifiManager)context
			.getSystemService(Context.WIFI_SERVICE);
			
			Log.i(TAG,"wifiEnable"+wifiManager.isWifiEnabled());
			return wifiManager.isWifiEnabled();
		}
		public static String getActiveNetWorkName( Context context ) {
		    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		    String result = null;
		    do {
		    	if (connectivity == null) {
		    		break;
		    	}
		    	
		    	NetworkInfo[] info = connectivity.getAllNetworkInfo();    
		        if (info != null) {        
		            for (int i = 0; i < info.length; i++) {           
		            	
		                if (info[i].getState() == NetworkInfo.State.CONNECTED) {              
		                	result = info[i].getTypeName(); 
		                }        
		            }     
		        }    
		    }while(false);
		   Log.i(TAG, "getActiveNetWorkName : "+ result);
		   return result;
		}
}
